import tkinter as tk
from tkinter import ttk, messagebox
from database import DB_NAME, verify_user, create_user
import sys


class LoginWindow:
    def __init__(self, root, callback):
        self.root = root
        self.root.geometry("400x300")
        self.root.title("小兔文档 - 登录")
        self.root.resizable(False, False)
        self.callback = callback
        
        # 设置窗口图标
        import os
        icon_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'icon.ico')
        if os.path.exists(icon_path):
            self.root.iconbitmap(icon_path)


        # 设置中文字体支持
        self.font_family = "Microsoft YaHei UI"
        self.default_font = (self.font_family, 10)
        self.title_font = (self.font_family, 16, "bold")


        # 设置背景颜色和主题
        self.bg_color = "#f0f2f5"
        self.accent_color = "#1a73e8"
        self.text_color = "#202124"
        self.root.configure(bg=self.bg_color)


        # 创建主框架并居中
        self.main_frame = ttk.Frame(root, padding=(40, 30), style="MainFrame.TFrame")
        self.main_frame.place(relx=0.5, rely=0.5, anchor="center")


        # 添加标题和副标题
        ttk.Label(self.main_frame, text="小兔文档", font=self.title_font, foreground=self.accent_color).grid(row=0, column=0, columnspan=2, pady=(0, 20))
        ttk.Label(self.main_frame, text="安全登录您的账户", font=(self.font_family, 10), foreground="#5f6368").grid(row=1, column=0, columnspan=2, pady=(0, 25))


        # 用户名输入框
        self.create_input_field("用户名", 2)


        # 密码输入框
        self.create_input_field("密码", 3, show="*")


        # 登录按钮
        self.login_btn = ttk.Button(
            self.main_frame, text="登录", command=self.login,
            style="AccentButton.TButton", width=20
        )
        self.login_btn.grid(row=4, column=0, columnspan=2, pady=(20, 10))


        # 注册按钮
        self.register_btn = ttk.Button(
            self.main_frame, text="注册", command=self.register,
            style="SecondaryButton.TButton", width=20
        )
        self.register_btn.grid(row=5, column=0, columnspan=2)


        # 配置样式
        self.setup_styles()


    def setup_styles(self):
        """配置界面样式"""
        style = ttk.Style()
        style.theme_use("clam")


        # 主框架样式
        style.configure("MainFrame.TFrame", background=self.bg_color)


        # 标签样式
        style.configure("TLabel", background=self.bg_color, foreground=self.text_color, font=self.default_font)


        # 输入框样式
        style.configure(
            "Custom.TEntry",
            padding=10,
            font=self.default_font,
            borderwidth=1,
            relief="solid"
        )
        style.map(
            "Custom.TEntry",
            bordercolor=[("focus", self.accent_color), ("!focus", "#dadce0")],
            relief=[("focus", "solid"), ("!focus", "solid")]
        )


        # 按钮样式
        style.configure(
            "AccentButton.TButton",
            background=self.accent_color,
            foreground="white",
            padding=10,
            font=(self.font_family, 10, "bold"),
            borderwidth=0,
            relief="flat"
        )
        style.map(
            "AccentButton.TButton",
            background=[("active", "#1967d2"), ("disabled", "#d2d2d2")]
        )


        style.configure(
            "SecondaryButton.TButton",
            background="#e8eaed",
            foreground=self.text_color,
            padding=10,
            font=(self.font_family, 10),
            borderwidth=0,
            relief="flat"
        )
        style.map(
            "SecondaryButton.TButton",
            background=[("active", "#d2d2d2"), ("disabled", "#f0f0f0")]
        )


    def create_input_field(self, label_text, row, show=""):
        """创建带标签的输入框"""
        ttk.Label(self.main_frame, text=label_text+"：", anchor="e").grid(row=row, column=0, sticky="e", padx=(0, 10), pady=8)
        entry = ttk.Entry(self.main_frame, width=25, show=show, style="Custom.TEntry")
        entry.grid(row=row, column=1, sticky="w", pady=8)
        if row == 2:  # 用户名输入框自动获取焦点
            entry.focus()
        setattr(self, label_text.lower(), entry)


    def login(self):
        # ... 现有登录逻辑保持不变 ...
        username = self.用户名.get().strip()
        password = self.密码.get().strip()


        if not username or not password:
            messagebox.showerror("错误", "用户名和密码不能为空！")
            return


        user_id = verify_user(username, password)
        if user_id:
            self.root.destroy()  # 关闭登录窗口
            self.callback(user_id)  # 回调打开主窗口
        else:
            messagebox.showerror("错误", "用户名或密码不正确！")


    def register(self):
        # ... 现有注册逻辑保持不变 ...
        username = self.用户名.get().strip()
        password = self.密码.get().strip()


        if not username or not password:
            messagebox.showerror("错误", "用户名和密码不能为空！")
            return


        if create_user(username, password):
            messagebox.showinfo("成功", "注册成功！请登录")
            self.用户名.delete(0, tk.END)
            self.密码.delete(0, tk.END)
        else:
            messagebox.showerror("错误", "用户名已存在！")


if __name__ == "__main__":
    root = tk.Tk()
    app = LoginWindow(root, lambda x: None)
    root.mainloop()